package com.andy.nature.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.andy.common.extend.setOnIMClickListener
import com.andy.common.model.Label
import com.andy.nature.BR
import com.andy.nature.R
import com.andy.nature.databinding.AdapterLabelItemGrayDeleteBinding

class CommonLabelAdapter : RecyclerView.Adapter<CommonLabelAdapter.BottomViewHolder>() {

    private var mContext: Context? = null
    private var selectLabel: Label? = null
    private var labelList = mutableListOf<Label>()
    private var actionListener: ActionListener? = null
    private var all = Label("", "全部", true)

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        mContext = recyclerView.context
    }

    fun setData(list: List<Label>?) {
        labelList.clear()
        selectLabel = all
        if (list?.contains(all) == false) {
            labelList.add(all)
        }
        if (!list.isNullOrEmpty()) {
            labelList.addAll(list)
        }
        notifyDataSetChanged()
    }

    fun getCommonLabelIds(): List<String> {
        val list = ArrayList<String>()
        labelList.forEach {
            it.id?.apply {
                list.add(this)
            }
        }
        return list
    }

    fun getCommonLabelList(): MutableList<Label> {
        return labelList
    }

    fun setActionListener(actionListener: ActionListener) {
        this.actionListener = actionListener
    }

    override fun getItemCount(): Int {
        return labelList.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BottomViewHolder {
        val binding = AdapterLabelItemGrayDeleteBinding.inflate(LayoutInflater.from(mContext), parent, false)
        return BottomViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BottomViewHolder, position: Int) {
        val data = labelList[position]
        DataBindingUtil.bind<AdapterLabelItemGrayDeleteBinding>(holder.itemView)?.let {
            it.setVariable(BR.grayDeleteLabelItem, data)
            it.executePendingBindings()
        }
        holder.binding.apply {
            if (selectLabel == data) {
                root.setBackgroundResource(R.drawable.dialog_shape_blue_r5)
            } else {
                root.setBackgroundResource(R.drawable.dialog_shape_stroke_e8e8e8_r5)
            }
            root.setOnIMClickListener {
                selectLabel = data
                actionListener?.click(data, labelList)
                notifyDataSetChanged()
            }
        }
    }

    class BottomViewHolder(val binding: AdapterLabelItemGrayDeleteBinding) : RecyclerView.ViewHolder(binding.root)

    interface ActionListener {
        fun click(data: Label, labelList: List<Label>)
    }
}